package _01_动态数组;

import java.util.Arrays;

public class _189_旋转数组 {

    public static void main(String[] args) {

        _189_旋转数组 v = new _189_旋转数组();

        int[] ins = {1,2,3,4,5,6,7};

        v.rotate(ins, 3);


        System.out.println(Arrays.toString(ins));

    }

    // 翻转数组
    public void rotate(int[] nums, int k) {
        // k可能会超过数组元素的长度
        k %= nums.length;
        // 翻转所有数组元素
        swap(nums, 0, nums.length - 1);
        // 翻转 0 - k - 1
        swap(nums, 0, k - 1);
        swap(nums, k, nums.length - 1);
    }

    // 翻转某一区间的数组元素
    public void swap(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start++] = nums[end];
            nums[end--] = temp;
        }
    }

    // 使用额外空间
    public void rotate1(int[] nums, int k) {
        int[] newAry = new int[nums.length];

        for (int i = 0; i < nums.length; i++) {
            newAry[(i + k) % nums.length] = nums[i];
        }
        System.arraycopy(newAry, 0, nums, 0, nums.length);
    }

}
